package com.cac.demo.controller.cemopHandoverForm;


import com.alibaba.fastjson.JSONObject;
import com.cac.demo.controller.FinProReceive.FinProReceiveSearchRest;
import com.cac.demo.controller.compressedFiles.CompressedFilesEditor;
import com.cac.demo.controller.materialScan.WmsDeliverPlanRest;
import com.cac.demo.controller.partReceive.PartReceiveRest;
import com.cac.demo.dao.materialScan.WmsDeliverPlanDao;
import com.cac.demo.newCode.cemop.service.Impl.CemopServiceImpl;
import com.cac.demo.service.bzjReceive.BZJReceiveService;
import com.cac.demo.service.cemopHandoverForm.CemopDeliverPlanService;
import com.cac.demo.service.materialScan.WmsDeliverPlanService;
import com.cac.demo.service.outStoreRoom.OutStoreMaterialRoomService;
import com.cac.demo.util.ExceptionToStirng;
import com.cac.demo.util.adapter.ResponseMsg;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/cemopHandoverForm")
@Slf4j
public class HandoverForm {
    @Autowired
    private CompressedFilesEditor compressedFilesEditor;
    @Autowired
    private CemopDeliverPlanService cemopDeliverPlanService;
    @Autowired
    private WmsDeliverPlanRest wmsDeliverPlanRest;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private PartReceiveRest partReceiveRest;
    @Autowired
    private FinProReceiveSearchRest finProReceiveSearchRest;
    @Autowired
    private OutStoreMaterialRoomService outStoreMaterialRoomService;
    @Autowired
    private BZJReceiveService bzjReceiveService;
    @Autowired
    private WmsDeliverPlanService wmsDeliverPlanService;
    @Autowired
    private WmsDeliverPlanDao wmsDeliverPlanDao;
    @Autowired
    private Environment environment;
    @Resource
    private CemopServiceImpl cemopServiceImpl;

    /**
     * Cemop产品预上账
     * @param jsonObject
     */
    @PostMapping("/GetHandoverForm")
    public HashMap GetHandoverForm(@RequestBody JSONObject jsonObject){
        System.out.println("=========================Cemop产品预上账==========================="+jsonObject);
        //园区网下发日志
        HashMap res = new HashMap();
        String fileUrl=jsonObject.get("fileUrl").toString();
        System.out.println("=========================下载zip文件并解析===========================");
        String str = String.valueOf(compressedFilesEditor.parseJsonFromZip(fileUrl));
        System.out.println("==========================文件内容==========================="+str);
        if (str.length()<20)
        {
            System.out.println("压缩文件为空");
            res.put("msg","解析失败"+str);
            res.put("success","false");
            return res;
        }
        jsonObject.put("description","Cemop产品预上账");
        ObjectMapper objectMapper = new ObjectMapper();
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            JsonNode json = objectMapper.readTree(str);
            System.out.println("=========================预上账数量==========================="+json.size());
            if (json.isArray())
            {
                for (JsonNode node : json)
                {
                    //添加物料基表数据
                    int MdsItem = cemopDeliverPlanService.AddCemopMdsItem(node);
                    System.out.println("================添加物料基表数据条数================"+MdsItem);
                    //交接单
                    int DeliverPlan = cemopDeliverPlanService.insertCemopAdvancePosting(node);
                    System.out.println("================添加交接单数据条数================"+DeliverPlan);
                    //质量信息表
                    int QualityInfo = cemopDeliverPlanService.insertCemopWmsQualityInfo(node);
                    System.out.println("================添加质量信息表数据条数================"+QualityInfo);
                }
            }
            else{
                //添加物料基表数据
                int MdsItem = cemopDeliverPlanService.AddCemopMdsItem(json);
                System.out.println("================添加物料基表数据条数================"+MdsItem);
                //产品预上账
                int DeliverPlan = cemopDeliverPlanService.insertCemopAdvancePosting(json);
                System.out.println("================添加交接单数据条数================"+DeliverPlan);
                //质量信息表
                int QualityInfo = cemopDeliverPlanService.insertCemopWmsQualityInfo(json);
                System.out.println("================添加质量信息表数据条数================"+QualityInfo);
            }

            res.put("msg","解析成功");
            res.put("success","true");
            platformTransactionManager.commit(transaction);
            jsonObject.put("msg","CEMOP系统扫码移交至101库存失败");
            jsonObject.put("status","2");
            cemopServiceImpl.sendSortBackResult(jsonObject);
            return res;
        } catch (Exception e) {
            jsonObject.put("msg","失败："+e);
            jsonObject.put("status","3");
            cemopServiceImpl.sendSortBackResult(jsonObject);
            res.put("msg","解析失败"+str);
            res.put("success","false");
            platformTransactionManager.rollback(transaction);
            throw new RuntimeException(e);
        }finally {
            return res;
        }
    }
    /**
     * 扫码移交*/
    @PostMapping("/changeAccType")
    public ResponseMsg<String> cemopChangeTransferType(@RequestBody Map map) throws ParseException {
        log.info("物料扫码移交接口：");
        try{
            //查询此物料信息所属系统（Cemop/ERP）
            String system = cemopDeliverPlanService.getSystemByBarcode(map.get("barcode").toString());
            if (system.equals("Cemop")){
                return cemopDeliverPlanService.changeTransferCemop(map);   //Cemop扫码移交
            }else {
                return wmsDeliverPlanRest.changeTransferType(map);     //ERP扫码移交
            }
        }
        catch (Exception e){
            log.error("物料扫码移交接口异常："+e.getMessage());
            return ResponseMsg.error("物料扫码移交接口异常："+e.getMessage());
        }
    }
    /**
     * 接收入库（通知Cemop系统）*/
    @PostMapping("/cemopReceiveStock")
    public ResponseMsg<String> cemopReceiveStock(@RequestBody HashMap map) {
        log.info("物料接收入库接口：");
        ResponseMsg<String> responseMsg = new ResponseMsg<>();

        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String receiveEmpCode = (String) request.getSession().getAttribute("account");
        if (Objects.isNull(receiveEmpCode)) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("登录过期，请重新登录！");
            return responseMsg;
        }
        String materialType = (String)map.get("materialType");
        map.put("IP",IP);
        // 创建一个数组
        ObjectMapper mapper = new ObjectMapper();
        List<JSONObject> list = new ArrayList<>();
        String CemopUrl = environment.getProperty("cemopUrl.receivePlan");
        //判断物料类型
        if ("LJ".equals(materialType)){
            TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
            try {
                List<HashMap> lists = (List<HashMap>) map.get("data");
                for(HashMap data :lists){
                    //改变接收状态
                    partReceiveRest.changeTransferType(data);
                    //定义json对象存储数据，打包发送到Cemop
                    JSONObject json = new JSONObject();
                    json.put("userId", receiveEmpCode); //接收人工号
                    json.put("momWmsDeliveryPlanId", data.get("wmsDeliveryPlanId").toString());//交接单id
                    json.put("momWmsItemInventoryId", data.get("WMS_ITEM_INVENTORY_ID").toString());//台账id
                    list.add(json);
                }
                //调用零件缓存箱出库
                responseMsg = outStoreMaterialRoomService.callBox(lists,IP);
                if(responseMsg.getRetCode().equals("201")){
                    platformTransactionManager.rollback(transaction);
                    return responseMsg;
                }
                System.out.println("====================接收入库=====================："+list);
                //将json转换为zip文件
                String zipUrl = compressedFilesEditor.generateZip(mapper.writeValueAsString(list));
                compressedFilesEditor.fileSend(list,zipUrl, CemopUrl,"接收入库（通知Cemop系统）");
                //全部成功提交事务
                platformTransactionManager.commit(transaction);
                return responseMsg;
            }catch (NullPointerException ne){
                ne.printStackTrace();
                platformTransactionManager.rollback(transaction);
                return responseMsg.setRetCode("201").setMessage("叫箱失败！请确认是否还有空箱！");
            }catch (Exception e){
                e.printStackTrace();
                platformTransactionManager.rollback(transaction);
                return responseMsg.setRetCode("201").setMessage("接收失败");
            }
        }else if ("CP".equals(materialType)) {
            TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
            try {
                List<HashMap> lists = (List<HashMap>) map.get("data");
                for(HashMap data :lists){
                    //改变接收状态
                    finProReceiveSearchRest.changeTransferType(data);
                    //定义json对象存储数据，打包发送到Cemop
                    JSONObject json = new JSONObject();
                    json.put("userId", receiveEmpCode); //接收人工号
                    json.put("momWmsDeliveryPlanId", data.get("wmsDeliveryPlanId").toString());//交接单id
                    json.put("momWmsItemInventoryId", data.get("WMS_ITEM_INVENTORY_ID").toString());//台账id
                    list.add(json);
                }
                //调用成品缓存箱出库
                responseMsg = outStoreMaterialRoomService.callBox(lists,IP);
                if(responseMsg.getRetCode().equals("201")){
                    platformTransactionManager.rollback(transaction);
                    return responseMsg;
                }
                System.out.println("====================成品接收入库=====================："+list);
                String zipUrl = compressedFilesEditor.generateZip(mapper.writeValueAsString(list)); //将json转换为zip文件

                compressedFilesEditor.fileSend(list,zipUrl, CemopUrl,"接收入库（通知Cemop系统）");
                //全部成功提交事务
                platformTransactionManager.commit(transaction);
                return responseMsg;
            }catch (NullPointerException ne){
                ne.printStackTrace();
                platformTransactionManager.rollback(transaction);
                return responseMsg.setRetCode("201").setMessage("叫箱失败！请确认是否还有空箱！");
            }catch (Exception e){
                e.printStackTrace();
                platformTransactionManager.rollback(transaction);
                return responseMsg.setRetCode("201").setMessage("接收失败");
            }
        }else if ("BZJ".equals(materialType)) {
            TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
            try {
                List<HashMap> lists = (List<HashMap>) map.get("data");
                for(HashMap data :lists){
                    //改变接收状态
                    bzjReceiveService.changeTransferType4Bzj((String)data.get("wmsDeliveryPlanId"),receiveEmpCode,IP);
                    //定义json对象存储数据，打包发送到Cemop
                    JSONObject json = new JSONObject();
                    json.put("userId", receiveEmpCode); //接收人工号
                    json.put("momWmsDeliveryPlanId", data.get("momWmsDeliveryPlanId").toString());//交接单id
                    json.put("momWmsItemInventoryId", data.get("WMS_ITEM_INVENTORY_ID").toString());//台账id
                    list.add(json);
                }
                //调用零件缓存箱出库
                responseMsg = outStoreMaterialRoomService.callBzjBox(lists,IP);
                if(responseMsg.getRetCode().equals("201")){
                    platformTransactionManager.rollback(transaction);
                    return responseMsg;
                }
                String zipUrl = compressedFilesEditor.generateZip(mapper.writeValueAsString(list)); //将json转换为zip文件下载路径
                compressedFilesEditor.fileSend(list,zipUrl, CemopUrl,"接收入库（通知Cemop系统）");
                //全部成功提交事务
                platformTransactionManager.commit(transaction);
                return responseMsg;
            }catch (NullPointerException ne){
                    ne.printStackTrace();
                    platformTransactionManager.rollback(transaction);
                    return responseMsg.setRetCode("201").setMessage("叫箱失败！请确认是否还有空箱！");
                }catch (Exception e){
                    e.printStackTrace();
                    platformTransactionManager.rollback(transaction);
                    return responseMsg.setRetCode("201").setMessage("接收失败").setErrorDesc(ExceptionToStirng.getExceptionToString(e));
                }
            }
        return responseMsg;
    }
    /**
     * 扫码退回（通知Cemop系统）*/
    @PostMapping("/changeRetrunType")
    public ResponseMsg<String> cemopScenBack(@RequestBody Map map) {
        //查询此物料信息所属系统（Cemop/ERP）
        String system = cemopDeliverPlanService.getSystemByBarcode(map.get("barcode").toString());
        if (system.equals("Cemop")){
            return cemopDeliverPlanService.cemopScenBack(map);   //Cemop扫码退回
        }else {
            return wmsDeliverPlanRest.changeRetrunType(map);     //ERP扫码退回
        }

    }
    //测试接口
    @PostMapping("/cemopTest")
    public ResponseMsg<String> cemopTest(@RequestBody Map map) {
        System.out.println("=============================测试接口_调用成功======================"+map);
        return null;
    }
}
